#!/usr/bin/env python
import os
import sys
import getopt
import time
import xiami_helper
import xiami_error

_verbose = False
_updatetag = False

def xiami_error_handler():
    if xiami_error.error_no != 0:
        print 'ERROR: %d, %s' %(xiami_error.error_no, xiami_error.error_msg)
        if xiami_error.error_abort:
            exit(xiami_error.error_no)
        xiami_error.error_no = 0

def xiami_downloader(playlist_url, save_dir):
    playlist = xiami_helper.parse_playlist(playlist_url)
    xiami_error_handler()
    for track in playlist:
        save_path = os.path.join(save_dir, track['title'][:20] + '.mp3')
        print 'downloading ', track['song_id'], save_path
        if _verbose:
            print 'from url: ', track['location']
        xiami_helper.download(track['location'], save_path)
        xiami_error_handler()
        if _updatetag:
            print 'updating tag: ', track['artist'], '-', track['title'], '@', track['album_name']
            xiami_helper.format_tag_id3v1(save_path, track)
            xiami_error_handler()
        time.sleep(1)

def xiami_download_player(player_url, save_dir):
    playlist_url = xiami_helper.get_playlist_url(player_url)
    xiami_error_handler()
    xiami_downloader(playlist_url, save_dir)

def xiami_download_ids(id_list, save_dir):
    playlist_url = xiami_helper.compose_playlist_url(id_list)
    xiami_error_handler()
    xiami_downloader(playlist_url, save_dir)

def usage():
    print 'Usage: ' + sys.argv[0] + ' -u player-url -s save-dir [--id=ID,ID,ID --verbose --updatetag]'
    print 'example: ' + sys.argv[0] + ' -u http://www.xiami.com/song/play?ids=/song/playlist/id/22925049/type/3 -s /tmp/mp3.tmp/'

if __name__ == '__main__':
    player_url = None
    save_dir = None
    ids = None
    # parse args
    opts, args = getopt.getopt(sys.argv[1:], 'hu:s:vt', ['hlep', 'player-url=', 'save-dir=', 'id=', 'verbose', 'updatetag'])
    for o, v in opts:
        if o in ['-h', '--help']:
            usage()
            exit(0)
        elif o in ['-u', '--player-url']:
            player_url = v
        elif o in ['-s', '--save-dir']:
            save_dir = v
        elif o in ['--id']:
            ids = v.split(',')
        elif o in ['-v', '--verbose']:
            _verbose = True
        elif o in ['-t', '--updatetag']:
            _updatetag = True
    # check args
    if save_dir is None:
        usage()
        exit(1)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
        print 'created', save_dir

    if not ids is None: # download ids
        xiami_download_ids(ids, save_dir)
    elif not player_url is None: # download player
        xiami_download_player(player_url, save_dir)
    else:
        usage()
        exit(1)

